package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.jwm.power.mapper.OperateMapper;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.*;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.*;
import com.jwm.power.service.MenusService;
import com.jwm.power.service.SysService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SysSearcherImpl implements SysService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private NoticesRepository noticesRepository;
    @Autowired
    private DicsRepository dicsRepository;
    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private OperateMapper operateMapper;

    //  设置字典
    @Override
    public ResponseData SaveDics(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            SysDics model_New = new SysDics();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            if (model_New.getParentcode() == null || model_New.getParentcode().equals("")) {
                model_New.setParentcode("00");
            }
            Integer operationType = 0;
            Integer changeParent = 0;
            if (model_New.getDicid() != null && model_New.getDicid() > 0) {
                operationType = 1;
                //  判断是否变更父级
                SysDics sysDics = dicsRepository.findByDicid(model_New.getDicid());
                if (!sysDics.getParentcode().equals(model_New.getParentcode())) {
                    //  检查当前字典是否有子集
                    List<SysDics> sysDicsList = dicsRepository.findByParentcode(model_New.getDiccode());
                    if (sysDicsList.size() > 0) {
                        return new ResponseData(EnumResult.DIC_FAIL_CHILD, model_New);
                    }
                    String maxCode = dicsRepository.getMaxCode(model_New.getParentcode());
                    maxCode = maxCode != null ? maxCode : "0";
                    String parentCode = model_New.getParentcode().equals("00") ? "" : model_New.getParentcode();
                    model_New.setDiccode(parentCode + String.format("%02d", Integer.parseInt(maxCode) + 1));
                    Integer sn_temp = dicsRepository.getMaxSn(model_New.getParentcode());
                    Integer sn = sn_temp != null ? sn_temp : 0;
                    model_New.setSn(sn + 1);
                    changeParent = 1;
                }
                //  检查是否更改字典名称
                if (!sysDics.getDicname().equals(model_New.getDicname())) {
                    List<SysDics> sysDicsList = dicsRepository.findByParentcodeAndDicname(model_New.getParentcode(), model_New.getDicname());
                    if (sysDicsList.size() > 0) {
                        return new ResponseData(EnumResult.DIC_FAIL_NAME, model_New);
                    }
                }
            } else {
                String maxCode = dicsRepository.getMaxCode(model_New.getParentcode());
                maxCode = maxCode != null ? maxCode : "0";
                String parentCode = model_New.getParentcode().equals("00") ? "" : model_New.getParentcode();
                model_New.setDiccode(parentCode + String.format("%02d", Integer.parseInt(maxCode) + 1));
                Integer sn_temp = dicsRepository.getMaxSn(model_New.getParentcode());
                Integer sn = sn_temp != null ? sn_temp : 0;
                model_New.setSn(sn + 1);
                //  判断同级下名称是否重复
                List<SysDics> sysDicsList = dicsRepository.findByParentcodeAndDicname(model_New.getParentcode(), model_New.getDicname());
                if (sysDicsList.size() > 0) {
                    return new ResponseData(EnumResult.DIC_FAIL_NAME, model_New);
                }
            }
            //  批量新增字典
            String dicsJson = request.getParameter("dicsJson");
            if (dicsJson.length() > 0) {
                Integer index = 1;
                Integer sn = model_New.getSn();
                String maxCode = model_New.getDiccode().substring(model_New.getDiccode().length() - 2);
                //  数据修改时获取当前最大编码和序号
                if (operationType == 1 && changeParent == 0) {
                    maxCode = dicsRepository.getMaxCode(model_New.getParentcode());
                    sn = dicsRepository.getMaxSn(model_New.getParentcode());
                }
                for (String dicName : dicsJson.split(",")) {
                    List<SysDics> sysDicsList = dicsRepository.findByParentcodeAndDicname(model_New.getParentcode(), dicName);
                    if (sysDicsList.size() == 0) {
                        SysDics sysDics = new SysDics();
                        String parentCode = model_New.getParentcode().equals("00") ? "" : model_New.getParentcode();
                        sysDics.setDiccode(parentCode + String.format("%02d", Integer.parseInt(maxCode) + index));
                        sysDics.setParentcode(model_New.getParentcode());
                        sysDics.setSn(sn + index);
                        sysDics.setDicname(dicName);
                        sysDics.setRemarks(model_New.getRemarks());
                        dicsRepository.save(sysDics);
                        index++;
                    }
                }
            }
            dicsRepository.save(model_New);

            //  添加日志
            Logs log = Ut.SaveLog("dics", model_New.getDicname(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }


    //  设置系统通知
    @Override
    public ResponseData SaveNotices(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            SysNotices model_New = new SysNotices();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);

            Integer operationType = 0;
            if (model_New.getId() != null && model_New.getId() > 0) {
                operationType = 1;
            }
            model_New.setCreatedate(Ut.getCurrentTime());
            model_New.setDateValidity(Ut.getAddTime(7));

            SysNotices sysNotices = noticesRepository.saveAndFlush(model_New);
            //  清空公告人员
            Map<String, Object> map = new HashMap<>();
            map.put("tName", "Sys_NoticesUser");
            map.put("strWhere", " nid=" + model_New.getId());
            operateMapper.deleteDefined(map);
            //  添加消息
            map = new HashMap<>();
            map.put("nid", sysNotices.getId());
            List<Users> usersList = new ArrayList<>();
            if (model_New.getTreecodes().length() > 0) {
                usersList = usersRepository.findByDeptcodeIn(sysNotices.getTreecodes().split(","));
            } else {
                usersList = usersRepository.findAll();
            }
            List<Integer> integerList = new ArrayList<>();
            for (Users model : usersList) {
                integerList.add(model.getUserid());
            }
            map.put("users", integerList);
            operateMapper.insertBatchNoticeUsers(map);   //  批量增加公告人员
            //  添加日志
            Logs log = Ut.SaveLog("notices", model_New.getContentUpdate(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  修改消息状态
    @Override
    public ResponseData UpdateMsgStatus(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            if (dataId != null && !dataId.equals("")) {
                Map<String, Object> map = new HashMap<>();
                map.put("tName", "Users_Messages");
                map.put("values", "jumpstatus=1");
                map.put("strWhere", " where id ='" + dataId + "'");
                operateMapper.updateDefined(map);   //
            }
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
}
